package com.wen.service.impl;

import cn.hutool.json.JSONUtil;
import com.wen.pojo.Auth;
import com.wen.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.wen.mapper.AuthMapper;
import com.wen.service.AuthService;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthServiceImpl implements AuthService{

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Auth> authTreeByUid(Integer userId) {
        String authTree = stringRedisTemplate.opsForValue().get("authTree:" + userId);
        if(authTree != null){
            //转为list->返回
            List<Auth> authListJSON = JSONUtil.toList(authTree, Auth.class);
            return authListJSON;
        }else{
            List<Auth> authList = authMapper.findAuthById(userId);
            List<Auth> authTreeList = allAuthToAuthTree(authList, 0);
            stringRedisTemplate.opsForValue().set("authTree:"+userId,JSONUtil.toJsonStr(authTreeList));
            return authTreeList;
        }
    }

    @Override
    public List<Auth> allAuthTreeByUid() {
        String authTree = stringRedisTemplate.opsForValue().get("authTree:all");
        if(authTree != null){
            //转为list->返回
            List<Auth> authListJSON = JSONUtil.toList(authTree, Auth.class);
            return authListJSON;
        }else{
            List<Auth> authList1 = authMapper.findAuthAll();
            List<Auth> authTreeList1 = allAuthToAuthTree(authList1, 0);
            stringRedisTemplate.opsForValue().set("authTree:all",JSONUtil.toJsonStr(authTreeList1));
            return authTreeList1;
        }
    }

    //将所有菜单List<Auth> 转成菜单树List<Auth>的递归算法
    private List<Auth> allAuthToAuthTree(List<Auth> allAuthList,Integer pid){

        //一级菜单
        List<Auth> firstLevelAuthList =new ArrayList<>();
        for (Auth auth:allAuthList){
            if(auth.getParentId().equals(pid)){
                firstLevelAuthList.add(auth);
            }
        }
        //拿到每一个一级菜单中所有的二级菜单
        for (Auth firstAuth: firstLevelAuthList){
            List<Auth> secondeLevelAuthList = allAuthToAuthTree(allAuthList, firstAuth.getAuthId());
            firstAuth.setChildAuth(secondeLevelAuthList);
        }

        return firstLevelAuthList;
    }
}
